
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
import axios from 'axios';
import qs from 'qs'
import {  getToken } from '@/libs/util'
var instance = axios.create();
instance.defaults.baseURL=baseUrl;
instance.defaults.timeout = 10000;
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

/****
 * 请求拦截器
 */
instance.interceptors.request.use(
    config => {
       
        let token=getToken();
        if (token) { 
            config.headers.Authorization = token;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    });
/**
 * 请求响应拦截
 * 主要对结果过虑非200状态的数据以及token失效后将重定向到登录页面
 */
instance.interceptors.response.use(
    response => {
        
        if(response.data.status==200){
            return response.data;
        } 
        switch(response.data.status){
           case 500:
             return Promise.reject("服务器繁忙,请稍候重式"); 
          default:
            return Promise.reject(response.data.message); 
        }
        
    });

export default {
    getBaseUrl(){
        return instance.defaults.baseURL;
    },
    fetchGet(url, params = {}) {
        console.info(qs.stringify(params))
        return new Promise((resolve, reject) => {
            instance.get(url+"?"+qs.stringify(params)).then(res => {
                resolve(res);
            }).catch(error => {
               
                reject(error);
            })
        })
    },
    fetchPost(url, params = {}) {
        return new Promise((resolve, reject) => {
            instance.post(url, qs.stringify(params)).then(res => {
                resolve(res);
            }).catch(error => {
                
                reject(error);
            })
        })
    }
}